
package com.gitee.jmash.rbac.dao;

import com.crenjoy.proto.utils.TypeUtil;
import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.core.orm.jpa.BaseDao;
import com.gitee.jmash.core.orm.jpa.SqlBuilder;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.rbac.entity.OpensEntity;
import com.gitee.jmash.rbac.entity.OpensEntity.OpensPk;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import jmash.rbac.protobuf.OpensReq;
import jmash.rbac.protobuf.OpensType;
import jmash.rbac.protobuf.UserOpensReq;
import org.apache.commons.lang3.StringUtils;

/**
 * Opens实体的Dao层（使用JPA实现）.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
public class OpensDao extends BaseDao<OpensEntity, OpensPk> {

  public OpensDao() {
    super();
  }

  public OpensDao(TenantEntityManager tem) {
    super(tem);
  }

  /**
   * 根据用户移除用户三方登录信息.
   */
  public int removeByUserId(UUID userId) {
    String sql = "delete from OpensEntity s where s.userId = ?1 ";
    return this.executeUpdate(sql, userId);
  }

  /**
   * 根据用户和三方登录类型移除用户三方登录信息.
   */
  public int removeByUserIdAndOpenType(UUID userId, OpensType openType) {
    String sql = "delete from OpensEntity s where s.userId = ?1 and s.openType = ?2 ";
    return this.executeUpdate(sql, userId, openType);
  }

  /**
   * 综合查询.
   */
  public List<OpensEntity> findListByReq(OpensReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select s ");
    return this.findListByParams(query, sqlBuilder.getParams());
  }

  /**
   * Create SQL By Req .
   */
  public SqlBuilder createSql(OpensReq req) {
    StringBuilder sql = new StringBuilder(" from OpensEntity s where 1=1  ");
    Map<String, Object> params = new HashMap<String, Object>();

    if (!TypeUtil.isEmpty(req.getUserId())) {
      sql.append(" and s.userId = :userId ");
      params.put("userId", UUIDUtil.fromString(req.getUserId()));
    }

    String orderSql = " order by s.createTime desc ";
    if (StringUtils.isNotBlank(req.getOrderName())) {
      orderSql = String.format(" order by %s %s ", req.getOrderName(),
          req.getOrderAsc() ? " asc " : " desc ");
    }

    return SqlBuilder.build().setSql(sql).setParams(params).setOrderSql(orderSql);
  }

  /**
   * 通过UnionId查询.
   */
  public OpensEntity findByUnionId(OpensType openType, String unionId) {
    String sql = "select s from OpensEntity s where s.openType=?1 and s.unionId = ?2";
    return this.findSingle(sql, openType, unionId);
  }

  /**
   * 通过OpenId查询.
   */
  public OpensEntity findByOpenId(OpensType openType, String appId, String openId) {
    String sql =
        "select s from OpensEntity s where s.openType=?1 and s.appId =?2 and s.openId = ?3";
    return this.findSingle(sql, openType, appId, openId);
  }

  /**
   * 获取用户登录某appId的unionId.
   */
  public List<String> findOpensUnionId(UserOpensReq request) {
    String sql =
        "select s.unionId from OpensEntity s where s.openType=?1 and s.appId =?2 and s.userId in ?3";
    Set<UUID> userIds = request.getUserIdList().stream().map(v -> UUIDUtil.fromString(v))
        .collect(Collectors.toSet());
    return this.findList(sql, String.class, request.getOpenType(), request.getAppId(), userIds);
  }

  /**
   * 获取用户开放平台绑定UnionId.
   */
  public List<String> findOpensUnionId(UUID userId) {
    String sql = "select s.unionId from OpensEntity s where s.userId = ?1";

    return this.findList(sql, String.class, userId);
  }
}
